package com.Vronsky.thread.test01;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.Test22")
public class Test22 {
    private static ReentrantLock lock=new ReentrantLock();

    public static void main(String[] args){
        //lock方法不可打断  lockInterruptibly方法 尝试获得锁的过程可被打断
        Thread thread = new Thread("t1") {
            @Override
            public void run() {
                try {
                    log.debug("尝试获得锁");
                    lock.lockInterruptibly();
                    log.debug("获取到锁");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    log.debug("没有获得锁");
                    return;
                } finally {
                    lock.unlock();
                }
            }
        };

        lock.lock();
        thread.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.debug("打断t1");
        thread.interrupt();
    }

    private static void m1(){
        lock.lock();
        try {
            log.debug("enter m1");
            m2();
        }finally {
            lock.unlock();
        }
    }

    private static void m2(){
        lock.lock();
        try {
            log.debug("enter m2");
        }finally {
            lock.unlock();
        }
    }
}
